package com.xiaoge.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoge.auth.annotation.ControllerEndpoint;
import com.xiaoge.response.Result;
import com.xiaoge.system.entity.File;
import com.xiaoge.system.entity.Log;
import com.xiaoge.system.service.LogService;
import com.xiaoge.system.vo.FileVo;
import com.xiaoge.system.vo.LogVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 操作日志表 前端控制器
 * </p>
 *
 * @author xiaoge
 * @since 2021-02-27
 */
@RestController
@RequestMapping("/log")
public class LogController {
    @Autowired
    private LogService logService;

    @ApiOperation(value = "分页查询操作日志")
    @PostMapping("/findLogPage")
    public Result findLogPage(@RequestParam(defaultValue = "1") Integer current,
                               @RequestParam(defaultValue = "7") Integer size,
                               @RequestBody LogVO logVO) {
        //取得分页条件
        Page<Log> page = new Page<>(current, size);
        //获得wragger
        QueryWrapper<Log> queryWrapper = getWrapper(logVO);
        //执行查询
        IPage<Log> filePage = logService.page(page, queryWrapper);

        long total = filePage.getTotal();
        List<Log> records = filePage.getRecords();
        return Result.ok().data("total", total).data("records", records);
    }


    /**
     * 删除单行日志
     *
     * @param id
     * @return
     */
    @ControllerEndpoint(exceptionMessage = "删除操作日志失败", operation = "删除操作日志")
    @ApiOperation(value = "删除操作日志")
    @PostMapping("/deleteLogById")
    public Result deleteLogById(Long id) {
        try {
            logService.removeById(id);
            return Result.ok();
        } catch (Exception e) {
            return Result.error();
        }
    }

    /**
     * 批量删除日志
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量删除操作日志")
    @PostMapping("/deleteLogsByIds")
    public Result deleteLogsByIds(String ids) {
        String[] idList = ids.split(",");
        logService.removeByIds(Arrays.asList(idList));
        return Result.ok().message("批量删除成功");
    }



    private QueryWrapper<Log> getWrapper(LogVO logVO) {
        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
        if (logVO != null) {
            //查询每个条件
            if (!ObjectUtils.isEmpty(logVO.getIp())) {
                queryWrapper.like("ip", logVO.getIp());
            }
            if (!ObjectUtils.isEmpty(logVO.getUsername())) {
                queryWrapper.like("username", logVO.getUsername());
            }
        }
        return queryWrapper.orderByDesc("create_time");
    }
}
